package com.lht.femalecat.netty.delimiter;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;

/**
 * @Author:骆宏图
 * @CreateDate: 10:16 2018/7/29.
 * @Description:
 * @Modified By:
 */
public class TimeClient {

    public static void main(String[] args){

        EventLoopGroup group=new NioEventLoopGroup();

        Bootstrap b=new Bootstrap();


        try {
            b.group(group).channel(NioSocketChannel.class).option(ChannelOption.SO_BACKLOG,100);
            b.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel socketChannel) throws Exception {
                    String separator="$";
                    ByteBuf buf=Unpooled.copiedBuffer(separator.getBytes());
                    socketChannel.pipeline().addLast(new DelimiterBasedFrameDecoder(1024,buf));
                    socketChannel.pipeline().addLast(new StringDecoder());
                    socketChannel.pipeline().addLast(new ClientHandler());
                }
            });
            ChannelFuture f=b.connect("127.0.0.1",8080).sync();
            f.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            group.shutdownGracefully();
        }

    }


    private static class ClientHandler extends ChannelInboundHandlerAdapter{
        public static int counter;
        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {
            String body="Query Time Order"+"$";
            for(int i=0;i<100;i++){
                ByteBuf buf= Unpooled.copiedBuffer(body.getBytes());
                ctx.writeAndFlush(buf);
            }

        }

        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
           String body=(String)msg;
            System.out.println("客户端接受内容："+body+",数量:"+ ++counter);
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            ctx.close();
        }
    }
}
